<?php
declare (strict_types=1);

namespace app\scan_bag\controller;

use app\admin\model\advertiser\AdvertiserThird;
use app\admin\model\advertiser\AdvertiserThirdLog;
use app\admin\model\base\User;
use app\admin\model\iot\ScanBagWay;
use app\admin\service\base\JwtService;
use app\BaseController;
use app\BaseService;
use app\Request;
use app\scan_bag\service\ScanBagV1Service;
use app\scan_bag\service\ScanBagV2Service;
use app\scan_bag\service\V1_Way_1_0Service;
use think\App;
use think\facade\Cache;
use think\response\Json;
use wechat\WsOfficialAccount;

/**
 * 微信V1_Way_4_2扫码取袋
 */
class V1_Way_4_2 extends BaseController
{

    /**
     * 当前扫码路径
     * @var string
     */
    private string $way = 'V1_Way_4_2';

    /**
     * 微信H5用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wechatLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->wechatH5Login2($code);
        if ($bool['bool']) {
            //签发token
            $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
            if ($jst_data['bool']) {
                return jsonReturn(1, $bool, '登录成功');
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }

    /**
     * 获取用户取袋次数并同步用户到客户
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function userScanNum(ScanBagV1Service $scanBagV1Service): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        return $scanBagV1Service->userScanNum($user_id, $mac_id);
    }

    /**
     * 微信上传经纬度信息
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function wechatLatLon(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接受参数
        $mac_id = $this->request->param('mac_id/s', '0');
        $latitude = $this->request->param('latitude/s', '0');
        $longitude = $this->request->param('longitude/s', '0');
        $accuracy = $this->request->param('accuracy/d', 0);    //位置精度
        //经纬度保存数据库
        $user_id = WS_USER_ID;
        //把地理位置信息保存至用户表
        User::userLocationRedis($user_id, $mac_id, $latitude, $longitude);
        //微信验证上传经纬度信息
        $bool = $v1_Way_1_0Service->wechatLatLon($mac_id, $latitude, $longitude);
        if ($bool) {
            return jsonReturn(1, [], '验证通过');
        }
        return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取。');
    }

    /**
     * 获取JSAPI配置
     * @return Json
     */
    public function jsApiConfig(): Json
    {
        //接受参数
        $url = $this->request->param('url/s', '');
        $obj = new WsOfficialAccount();
        $data = $obj->getJsApi($url);;
        return jsonReturn(1, $data);
    }

    /**
     * 获取推广微信小程序
     * @return Json
     */
    public function getWechatApplet(): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //通过mac_id获取路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '当前设备路径错误,请联系管理员!');
        }
        //判断需要验证取袋路径
        if ($WayInfo and $WayInfo['third_mini']) {
            //获取推广小程序信息
            $Third = AdvertiserThird::getIDThird($WayInfo['third_mini']);
            if ($Third and !in_array($mac_id, $Third['prohibit']) and $Third['mini_ogh'] and $Third['mini_appid']) {
                $temp = [
                    'way' => $WayInfo['key'],
                    'third_id' => $Third['id'],
                    'type' => $Third['type'],
                    'mini_name' => $Third['mini_name'],
                    'mini_ogh' => $Third['mini_ogh'],
                    'mini_appid' => $Third['mini_appid'],
                    'mini_link' => $Third['mini_link'],
                ];
                //写入统计
                AdvertiserThirdLog::writeMiniprogramLog($user_id, $Third['id'], $mac_id);
                //标记取袋安全码
                $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 1);
                if (!$SafeCode) {
                    return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
                }
                return jsonReturn(1, $temp);
            }
        }
        return jsonReturn(0, [], '路径参数错误');
    }

    /**
     * 微信取袋码出袋
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function postOutBag(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $sleep = $this->request->param('sleep/d', 22);
        $mac_id = $this->request->param('mac_id/s', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '设备ID错误');
        }
        //验证当前设备取袋路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '当前设备路径错误,请联系管理员!');
        }
        //获取用户信息
        $User = User::getIdUserInfo($user_id);
        if (!$User) {
            return jsonReturn(0, [], '用户信息错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2, true);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        //验证地理位置,获取缓存当前用户经纬度
        $LatLon = Cache::get(BaseService::generateLocationKey($user_id));
        $LatLon = $LatLon ?: ['latitude' => '', 'longitude' => ''];
        $bool = $v1_Way_1_0Service->wechatLatLon($mac_id, $LatLon['latitude'], $LatLon['longitude']);
        if (!$bool) {
            return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取。');
        }
        //生成取袋码
        $waycode = ScanBagV2Service::generateBagOutWaycode($User, $WayInfo['key'], $mac_id);
        //延迟出袋
        sleep($sleep);
        $scanBagV1Service = new ScanBagV1Service();
        return $scanBagV1Service->outBagWaycodeToV1($waycode, $this->way);
    }

    /**
     * 发起微信支付
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function wechatPayOrder(ScanBagV1Service $scanBagV1Service): Json
    {
        $mac_id = $this->request->param('mac_id');
        if (!$mac_id) {
            return jsonReturn(0, [], '设备信息错误');
        }
        return $scanBagV1Service->payOrderToV1(WS_USER_ID, $mac_id);
    }

    /**
     * 判断是否打开位置限制
     * @return Json
     */
    public function locationLimit():Json
    {
        $mac_id = $this->request->param('mac_id/s','');
        //判断参数
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //通过mac_id获取路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if($WayInfo && $WayInfo['location_limit']){
            return jsonReturn(1, ['location_limit'=>$WayInfo['location_limit']]);
        }
        return jsonReturn(1, ['location_limit'=>0]);
    }


}
